package com.cairenhui.trust.auto.task.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.cairenhui.trust.auto.task.dao.BaseOrganizationMapper;
import com.cairenhui.trust.auto.task.dao.BaseSysUserMapper;
import com.cairenhui.trust.auto.task.dao.CrmDepartVMapper;
import com.cairenhui.trust.auto.task.dao.CrmSysUserVMapper;
import com.cairenhui.trust.auto.task.dao.FuncRoleMapper;
import com.cairenhui.trust.auto.task.model.BaseOrganization;
import com.cairenhui.trust.auto.task.model.BaseOrganizationExample;
import com.cairenhui.trust.auto.task.model.BaseSysUser;
import com.cairenhui.trust.auto.task.model.BaseSysUserExample;
import com.cairenhui.trust.auto.task.model.CrmDepartV;
import com.cairenhui.trust.auto.task.model.CrmDepartVExample;
import com.cairenhui.trust.auto.task.model.CrmSysUserV;
import com.cairenhui.trust.auto.task.model.CrmSysUserVExample;
import com.cairenhui.trust.auto.task.model.FuncRole;
import com.cairenhui.trust.auto.task.model.FuncRoleExample;
import com.cairenhui.trust.auto.task.model.Page;
import com.cairenhui.trust.auto.task.service.TaskService;
import com.cairenhui.trust.auto.task.util.DateUtils;
import com.cairenhui.trust.auto.task.util.TrustPropertyConfigurer;
import com.cairenhui.trust.auto.task.util.constant.StatusConstants;

/**
 * 
 * @author 黄瑞庆
 * TODO 员工信息更新任务
 * 2017年2月27日
 */
@Component
public class BaseSysUserTaskService extends TaskService{
	
	//self4j日志
	private Logger logger = LoggerFactory.getLogger(BaseSysUserTaskService.class);
	
	@Autowired
	private CrmDepartVMapper  crmDepartVMapper;
	@Autowired
	private FuncRoleMapper funcRoleMapper;
	@Autowired
	private CrmSysUserVMapper crmSysUserVMapper;
	@Autowired
	private BaseSysUserMapper  baseSysUserMapper;
	@Autowired
	private BaseOrganizationMapper baseOrganizationMapper;
	/** 
	 * 
	 * TODO 同步 更新员工信息方法
	 * @author 黄瑞庆
	 * 2017年3月2日 下午6:56:10
	 */
	@Override
	public void sysCrm() {
		//中融财富中心及隶属部门编号
		String zrCenterDeptCode = (String) TrustPropertyConfigurer.getContextProperty("zr.center.dept.code");
		CrmDepartVExample crmDepartVExample = new CrmDepartVExample();
		crmDepartVExample.createCriteria().andCParentdeptcodeLike("%"+zrCenterDeptCode+"%");
		crmDepartVExample.or().andCDeptcodeEqualTo(zrCenterDeptCode);
		//获取同步视图数据 （营业部门信息）
		List<CrmDepartV> listDepart = crmDepartVMapper.selectByExample(crmDepartVExample);
		List<String> listCrmDeptCode = new ArrayList<String>();
		for(CrmDepartV crmDept : listDepart ){
			listCrmDeptCode.add(crmDept.getcDeptcode());
		}
		//角色号
		String roleCode =  (String) TrustPropertyConfigurer.getContextProperty("role.code");
		FuncRoleExample funcRoleExample = new FuncRoleExample();
		funcRoleExample.createCriteria().andRoleCodeEqualTo(roleCode);
		List<FuncRole> listFuncRole =  funcRoleMapper.selectByExample(funcRoleExample);
		FuncRole funcRole = null;
		if(listFuncRole.size() == 0){
			logger.error(this.getClass().getSimpleName() + "  " + "err:无理财角色");
		}else{
			funcRole = listFuncRole.get(0);
		}
		
		//每次查询条数 QUERY_NUM
		//获取员工总数 TOTAL_COUNT
		CrmSysUserVExample crmSysUserVExample = new CrmSysUserVExample();
		TOTAL_COUNT = crmSysUserVMapper.countByExample(crmSysUserVExample);
		//根据每页查询数 ，总条数 计算出 总页数
		Page<CrmSysUserV> pageTemp = new Page<CrmSysUserV>(1, QUERY_NUM,TOTAL_COUNT);
		
		//开启分页查询
		for(int i = 1 ; i<= pageTemp.getTotalPage() ; i++){
			List<BaseSysUser> insertList = new ArrayList<BaseSysUser>();
			List<BaseSysUser> updateList = new ArrayList<BaseSysUser>();
			
			//同步时间
			String sysTime = DateUtils.getStrDate(new Date(), DateUtils.STRDATE_1+DateUtils.HOURS_MINUTES_SECONDS);
			
			Page<CrmSysUserV> page = new Page<CrmSysUserV>(i, QUERY_NUM,TOTAL_COUNT);
			crmSysUserVExample.setPage(page);
			List<CrmSysUserV> listCrmSysUserV = crmSysUserVMapper.selectByExample(crmSysUserVExample);
			
			//本地员工信息查询  插入或更新 （通过员工号查询）
			List<String> listEmpNo = new ArrayList<String>();
			for(CrmSysUserV csu :listCrmSysUserV){
				listEmpNo.add(csu.getcBrokeraccount());
			}
			BaseSysUserExample baseSysUserExample = new BaseSysUserExample();
			baseSysUserExample.createCriteria().andEmpNoIn(listEmpNo);
			List<BaseSysUser> listBaseSysUser =  baseSysUserMapper.selectByExample(baseSysUserExample);
			Map<String,Object> mapBaseSysUser = new HashMap<String, Object>();
			for(BaseSysUser bsu : listBaseSysUser){
				mapBaseSysUser.put(bsu.getEmpNo(),bsu);
			}
			
			for(CrmSysUserV csu :listCrmSysUserV){
				BaseSysUser sysUser = (BaseSysUser) mapBaseSysUser.get(csu.getcBrokeraccount());
				if(sysUser == null){
					sysUser = new BaseSysUser();
				}
				//校验数据
				sysUser.setEmpType("1");
				sysUser.setEmpNo(csu.getcBrokeraccount());
				sysUser.setEmpName(csu.getcBrokername());
				sysUser.setMail(csu.getcEmail());
				sysUser.setMobile(csu.getcMobile());
				
				String crmOrgCode = csu.getcDeptnodecode();
				//获取部门信息
				BaseOrganizationExample baseOrganizationExample = new BaseOrganizationExample();
				baseOrganizationExample.createCriteria().andOrgCodeEqualTo(crmOrgCode);
				List<BaseOrganization> listBaseOrg = baseOrganizationMapper.selectByExample(baseOrganizationExample);
				BaseOrganization baseOrg = null;
				if(listBaseOrg.size() == 0){
					logger.error(this.getClass().getSimpleName() + "  " + "err:无部门信息,部门编号{}",crmOrgCode);
				}else{
					baseOrg = listBaseOrg.get(0);
				}
				if(baseOrg != null){
					sysUser.setOrgId(baseOrg.getOrgId());
				}
				if("0".equals(csu.getcStatus())){
					sysUser.setStatus(StatusConstants.CREATED);
				}else if("1".equals(csu.getcStatus())){
					sysUser.setStatus(StatusConstants.CANCEL);
				}
				sysUser.setEmpLoginName(csu.getcUsercode());
				//角色
				//判断是否为中融财富中心隶属部门，设置员工角色
				if(listCrmDeptCode.contains(csu.getcDeptnodecode()) && funcRole != null){
					sysUser.setRoleId(null == funcRole.getRoleId2() ? "" : funcRole.getRoleId2().toString());
				}
				//添加 更新
				if( null == sysUser.getEmpId() ){
					sysUser.setCreateTime(new Date());
					sysUser.setUpdateTime(new Date());
					insertList.add(sysUser);
				}else{
					sysUser.setUpdateTime(new Date());
					updateList.add(sysUser);
				}
			}
			
			if (updateList.size() > 0) {
				inserOrUpdate(updateList,false);
			}
			if (insertList.size() > 0) {
				inserOrUpdate(insertList,true);
			}
			logger.info("员工信息>>>>>>第{}次同步，--->同步条数{}，同步时间{}",i,listCrmSysUserV.size(),sysTime);
		}
		
		
		
	}
	
	/**
	 * 
	  * TODO 循环插入 或 更新
	 * @author 黄瑞庆
	 * void
	 * @param list 出入对象集合
	 * @param isInsert true:插入
	 * 2017年3月3日 下午12:24:01
	 */
	public void inserOrUpdate(List<BaseSysUser> list , Boolean isInsert){
		for(BaseSysUser baseSysUser : list){
			if(isInsert){
				baseSysUserMapper.insertSelective(baseSysUser);
			}else{
				baseSysUserMapper.updateByPrimaryKeySelective(baseSysUser);
			}
		}
	}
	

}
